﻿import { _decorator, Component, Node, input, Input, EventKeyboard, KeyCode, loader, assetManager, Texture2D, SpriteFrame, Sprite } from 'cc';
import { ComBase } from '../base/ComBase';
import { SysMgr } from '../common/SysMgr';
import { TimeSys } from '../sys/TimeSys';
import { EventSys } from '../sys/EventSys';
import { WsSys } from '../sys/WsSys';
import { Defines } from '../common/Defines';


const { ccclass, property } = _decorator;

@ccclass('WsCom')
export class WsCom extends ComBase {
    ws: WebSocket;
    isSucc = false;
    funcMap = new Map<string, Map<any, Array<string>>>();
    wsUrl: string


    wsSys: WsSys;
    isNormalClose = false;
    init(wsUrl: string) {
        this.wsUrl = wsUrl

        this.wsSys = SysMgr.getSys(WsSys);
        this.initWs()
        SysMgr.getSys(TimeSys).addTimer(this, "_heart", 5, true);
        SysMgr.getSys(TimeSys).addTimer(this, "_reConn", 3, true);

        return this;
    }

    initWs() {
        this.isNormalClose = false;
        this.ws = new WebSocket(this.wsUrl);
        var self = this;
        this.ws.onopen = function (event) {
            console.log("连接成功！", event, this);
            self.initSucc();
        }

        this.ws.onmessage = async function (event) {
            let data = JSON.parse(event.data)
            self.wsSys.recvData(data)
        }

        this.ws.onclose = async function onclose(event) {
            self.isSucc = false;
            console.log("关闭！", event);
        }
    }

    close() {
        this.isNormalClose = true;
        SysMgr.getSys(TimeSys).removeTimer(this, "_heart");
        SysMgr.getSys(TimeSys).removeTimer(this, "_reConn");
        this.ws.close()
    }

    reConn() {
        if (this.isSucc)
            return
        this.initWs()
    }

    _reConn() {
        this.reConn()
    }

    _heart() {
        this.sendMsg(Defines.C2S_COMMON,"heart", {})
    }


    initSucc() {
        this.isSucc = true;

    }

    sendMsg(type, api, data) {
        if (!this.isSucc)
            return;
        data.type = type
        data.func = api
        //this.data_arr.push(data)
        this.ws.send(JSON.stringify(data));
    }



}

